<?php
class Position_model extends HYD_Model {
    private $_sql_where = '';

    public function __construct(){
        $this->set_table_name('position');
    }

    /**
     * 获取已有数据
     *
     * 根据岗位ID和管理员用户名获取指定管理员数据
     * @param	string $positionname 管理员用户名
     * @return	array 结果集
     */
    public function get_data_positionname( $positionname = '') {
        $feild_list = $this->get_all_feilds();
        $this->db->select($feild_list);
        $this->db->from($this->get_table_name());
        $this->db->where(array('positionname' => $positionname));
        $result_list = $this->db->get();
        return $result_list->row_array();
    }
    
    /**
     * 获取用户记录
     *
     * 根据ID获取指定一条管理员记录
     * @param	 string id 权限ID
     * @return	 array 结果集
     */
    public function get_data($id) {
        $feild_list = $this->get_all_feilds();
        $where['id'] = $id;
        $result_data = $this->db
                ->select($feild_list)
                ->from($this->get_table_name())
                ->where($where)
                ->get();
        return $result_data->row_array();
    }
    /**
     * 保存岗位数据
     *
     * 更新或插入组数据,$id为NULL时插入，反之更新
     * @param	string id 组ID
     * @param	array $data 数据
     * @return	integer  1=成功 -3=岗位已存在  MODEL_RETURN_DBERROR=数据库错误
     */
    public function save($id = 0, $data) {
        $feild_array = array('id_value' => $id);
        $feild_array['where'] = array('name' => $data['name']);
        if ($this->get_is_duplicate($feild_array)) {
            return -3;
        }
        
        //事务开始
        $this->db->trans_begin();
        $row_data = $this->get_update_feilds($data);

        if ($id>0) {
            $where['id'] = $id;
            $this->db->update($this->get_table_name(), $row_data, $where);
        } else {
            $this->db->insert($this->get_table_name(), $row_data);
        }
        if ($this->check_dbtrans() === FALSE) {
            return MODEL_RETURN_DBERROR;
        }
        
        if(isset($data['module']) && count($data['module']) > 0) {
            if ($id==0) {//取刚插入的id
                $arr = $this->get_data_unique($data['name']);
                $id = $arr['id'];               
            }           
            $this->save_module($id, $data['module']);
        }
        //事务结束
        $this->db->trans_commit();
        return MODEL_RETURN_SUCCESS;
    }

    /**
     * 保存岗位的模块资源
     * @param type 
     */
    private function save_module($positionid = 0, $resource_arr = array()) {
        //log_message('error', $positionid.'-'.print_r($resource_arr,1));      

        $fd_acl_arr = array('add', 'edit', 'delete', 'import', 'export');       
        $post_res_arr = array();
        foreach ($resource_arr as $k => $module_arr) {
            $post_res_arr[] = $module_arr['module'];
            $fd_acl = '';
            if ($module_arr['checked']) {//更新或添加
                foreach ($fd_acl_arr as $acl) {
                    if ($module_arr[$acl]) {
                        $fd_acl .= $acl . ',';
                    }
                }                
                $resource = $this->get_resource($positionid, $module_arr['module']);
                $data_arr = array(
                    'module' => $module_arr['module'],
                    'acl' => rtrim($fd_acl, ',') 
                );
                if ($resource) {
                    $this->db->update('position_module', $data_arr, array('id' => $resource['id']));
                } else {
                    $data_arr['positionid'] = $positionid;
                    $this->db->insert('position_module', $data_arr);
                }
            } else {//删除-模块未选择
                $this->db->delete('position_module', array('positionid' => $positionid, 'module' => $module_arr['module']));
            }
            if ($this->check_dbtrans() === FALSE) {
                return MODEL_RETURN_DBERROR;
            }           
        }
        //删除表中无效记录
        $resource = $this->get_resource($positionid);
        foreach ($resource as $row) {
            if (!in_array($row['module'], $post_res_arr)) {
                $this->db->delete('position_module', array('positionid' => $positionid, 'module' => $row['module']));
            }
        }        
    }
    
    /**
     * 设置用户登录标志
     *
     * 根据ID设置用户登录标志
     * @param	 string id 管理员ID
     * @param	 bool $staus 状态
     * 
     * @return	 mixed TRUE==成功  MODEL_RETURN_DBERROR=数据库错误
     */
    public function set_is_login($id, $staus = FALSE) {
        if ($staus == TRUE) {
            $staus = 'YES';
        } else {
            $staus = 'NO';
        }
        $this->db->trans_begin();
        $this->db->update($this->get_table_name(), array('islogin' => $staus), array('id' => $id));
        if ($this->check_dbtrans() === FALSE) {
            return MODEL_RETURN_DBERROR;
        }
        $this->db->trans_commit();
        return TRUE;
    }
    
    /**
     * 根据唯一索引取单条数据
     * @param type $name
     * @return type
     */
    public function get_data_unique($name) {
        $feild_list = $this->get_all_feilds();
        
        $where['name'] = $name; 
       
        $result_data = $this->db
                ->select( $feild_list )
                ->from($this->get_table_name())
                ->where($where)
                ->get();
        return $result_data->row_array();
    }
    /**
     * 取已经分配模块资源
     * @param type $fd_groupid
     * @return array
     */
    public function get_resource( $positionid, $module = NULL) {   
        $where['positionid'] = $positionid;
        if(!is_null($module)) {
            $where['module'] = $module;
        }
        $this->db->select('id, module, acl');
        $this->db->from('position_module');          
        $this->db->where($where); 
        $result_list = $this->db->get();
        if (!is_null($module)) {
            return $result_list->row_array();
        } else {
            return $result_list->result_array();
        }
    }    
    /**
     * 获取数据列表
     *
     * 根据分页条件获取数据列表
     * @param	string $start 记录开始位置
     * @param	string $limit 记录数
     * @return	 array 结果集
     */
    public function get_lists($start = NULL, $limit = NULL, $sql_str = '', $root_show_flag = FALSE) {
        $feild_list = $this->get_all_feilds();
        $this->db->select($feild_list);
        $this->db->from($this->get_table_name());
        $where_str = '';
        if ($root_show_flag == FALSE) {
            $where_str = 'id>0';
        }
        //搜索处理      
        if (strlen($sql_str) > 0) {
            if ($where_str) {
                $where_str .= " and ( {$sql_str} )";
            } else {
                $where_str = $sql_str;
            }
        }

        if ($where_str) {
            $this->_sql_where = $where_str;
            $this->db->where($where_str, NULL, FALSE);
        }
        $this->db->order_by('id');

        if (!(is_null($start) && is_null($limit))) {
            $this->db->limit($limit, $start);
        }
        $result_list = $this->db->get();
        return $result_list->result_array();
    }

    /**
     * 获取记录总数
     * @return	 integer 
     */
    public function get_total() {
        if ($this->_sql_where){
            $this->db->where($this->_sql_where, NULL, FALSE);
        }
        return $this->db->count_all_results($this->get_table_name());
        //return $this->db->count_all($this->get_table_name());
    }
    
    public function get_module_ext_json_tree($positionid = 0){
        $show_acl_chk_arr = array('add', 'edit', 'delete', 'import', 'export');
        
        $this->load->helper('hyd_array');
        $module_group_arr = array();
        $module_group_arr2 = array();
        $module_group_data = array();  
        if($positionid == 0){
            $this->load->model("module/module_model");
            $module_group_arr = $this->module_model->get_select_arr(0);
            $i = 0;
            foreach ($module_group_arr as $group => $module_arr) {
                $module_group_arr2 = $this->module_model->get_select_arr($module_arr['id']); //二级子
                foreach ($module_group_arr2 as $arr => $module){
                    $module_group_data[$i]['group'] = $module_arr['text'];
                    $module_group_data[$i]['module'] = $module['name'];
                    $module_group_data[$i]['module_title'] = $module['text'];
                    $module_group_data[$i]['checked'] = FALSE;
                    foreach ($show_acl_chk_arr as $key=>$value){
                        $module_group_data[$i][$value] = FALSE;
                    }
                    $i++;
                }
            }      
        }else{
            $this->load->model("module/module_model");
            $module_group_arr = $this->module_model->get_select_arr(0);
            $i = 0;
            foreach ($module_group_arr as $group => $module_arr) {
                $module_group_arr2 = $this->module_model->get_select_arr($module_arr['id']); //二级子
                foreach ($module_group_arr2 as $arr => $module){
                    $module_group_data[$i]['group'] = $module_arr['text'];
                    $module_group_data[$i]['module'] = $module['name'];
                    $module_group_data[$i]['module_title'] = $module['text'];
                    $resource = $this->get_resource($positionid, $module['name']);
                    if($resource){
                        $module_group_data[$i]['checked'] = TRUE;
                        $acl_arr = explode(',', $resource['acl']);
                    }else{
                        $module_group_data[$i]['checked'] = FALSE;
                    }
                    
                    foreach ($show_acl_chk_arr as $key=>$value){
                        if($resource && in_array($value, $acl_arr)){
                            $module_group_data[$i][$value] = TRUE;
                        }else{
                            $module_group_data[$i][$value] = FALSE;
                        }
                    }
                    $i++;
                }
            }   
        }
        
        return $module_group_data;
    }
    
    
}